package io.lvdaxian.mybatis12.scripting.xmltags;

import io.lvdaxian.mybatis12.builder.BaseBuilder;
import io.lvdaxian.mybatis12.mapping.SqlSource;
import io.lvdaxian.mybatis12.scripting.defaults.RawSqlSource;
import io.lvdaxian.mybatis12.session.Configuration;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.List;

/**
 * xml 脚本的构建器
 *
 * @author lihh
 */
public class XMLScriptBuilder extends BaseBuilder {
  
  private final Element element;
  private boolean isDynamic;
  private final Class<?> parameterType;
  
  public XMLScriptBuilder(Configuration configuration, Element element, Class<?> parameterType) {
    super(configuration);
    this.element = element;
    this.parameterType = parameterType;
  }
  
  /**
   * 解析 脚本节点
   *
   * @return sql源
   * @author lihh
   */
  public SqlSource parseScriptNode() {
    List<SqlNode> sqlNodes = parseDynamicTags(element);
    MixedSqlNode rootSqlNode = new MixedSqlNode(sqlNodes);
    return new RawSqlSource(configuration, rootSqlNode, parameterType);
  }
  
  /**
   * 解析 动态tag
   *
   * @param element el 元素
   * @return 返回 sqlNode 集合
   * @author lihh
   */
  public List<SqlNode> parseDynamicTags(Element element) {
    // 标签节点 集合
    // 这里之所以用集合 是存在动态sql
    List<SqlNode> contents = new ArrayList<>();
    
    // element.getText 拿到 SQL eg: select * from xx 这是一个sql 文本
    String data = element.getText();
    contents.add(new StaticTextSqlNode(data));
    return contents;
  }
}
